package indi.zhang.rabbitmq.config;

import indi.zhang.mq.api.Producer;
import indi.zhang.rabbitmq.utils.RabbitMqProducer;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.ConsumerTagStrategy;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

import java.util.UUID;

public class MqConfig {

    @Bean
    @ConditionalOnProperty(value = "indi.zhang.common.rabbit",matchIfMissing = true, havingValue = "true")
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        // template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }

    @Bean("rabbitListenerContainerFactory")
    @ConditionalOnProperty(value = "indi.zhang.common.rabbit",matchIfMissing = true, havingValue = "true")
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }
    @Bean
    @ConditionalOnProperty(value = "indi.zhang.common.rabbit",matchIfMissing = true, havingValue = "true")
    public Producer producer(RabbitTemplate rabbitTemplate) {
        return new RabbitMqProducer(rabbitTemplate);
    }

    @Bean("consumerBatchContainerFactory")
    @ConditionalOnProperty(value = "indi.zhang.common.rabbit",matchIfMissing = true, havingValue = "true")
    public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory(ConnectionFactory rabbitConnectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(rabbitConnectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setConsumerTagStrategy(new ConsumerTagStrategy() {
            @Override
            public String createConsumerTag(String queue) {
                return queue + "_" + UUID.randomUUID().toString();
            }
        });
        factory.setBatchListener(true); // configures a BatchMessageListenerAdapter
        factory.setBatchSize(100);
        factory.setConsumerBatchEnabled(true);
        // 定时触发任务的间隔，不设置为0，设置以后每一个时间间隔触发一次拉取，不过可能存在消息积压的情况，可以把批次数量调大一些
        factory.setReceiveTimeout(30000L);
        return factory;
    }

}
